package dl.domainmodel.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import dl.martinfowler.wrapper.MfDate;
import dl.martinfowler.wrapper.Money;

public class Contract {

	private static long contractId = 1l;
	{
		contractId++;
	}

	private Product product;
	private Money revenue;
	private MfDate whenSigned;
	private Long id;

	private List<RevenueRecognition> revenueRecognitions = new ArrayList<RevenueRecognition>();

	public static List<Contract> contractList = new ArrayList<Contract>();

	public Contract(Product product, Money revenue, MfDate whenSigned) {
		super();
		this.product = product;
		this.revenue = revenue;
		this.whenSigned = whenSigned;
		this.id = contractId;
		// contractList.add(this);
	}

	public Money recognizedRevenue(MfDate asOf) {
		Money result = Money.dollars(0);
		Iterator<RevenueRecognition> it = revenueRecognitions.iterator();
		while (it.hasNext()) {
			RevenueRecognition recognition = (RevenueRecognition) it.next();
			if (recognition.isRecognizableBy(asOf)) {
				result = result.add(recognition.getAmount());
			}
		}
		return result;
	}

	public void addRevenueRecognition(RevenueRecognition revenueRecognition) {
		revenueRecognitions.add(revenueRecognition);

	}

	public void calculateRecognitions() {
		product.calculateRevenueRecognitions(this);
	}

	public static Contract find(Long id) {
		Iterator<Contract> contractItr = contractList.iterator();
		while (contractItr.hasNext()) {
			Contract contract = contractItr.next();
			if (contract.id.equals(id)) {
				return contract;
			}
		}
		return null;
	}

	public static long save(Contract contract) {
		contractList.add(contract);
		return contract.getId();
	}

	public static void delete(Long id) {
		contractList.remove(find(id));
	}

	public Long getId() {
		return id;
	}

	public Product getProduct() {
		return product;
	}

	public Money getRevenue() {
		return revenue;
	}

	public MfDate getWhenSigned() {
		return whenSigned;
	}

	public List<RevenueRecognition> getRevenueRecognitions() {
		return revenueRecognitions;
	}

	@Override
	public String toString() {
		return this.id + ":" + this.product.getName() + ":"
				+ this.revenue.amount() + ":" + this.whenSigned.toSqlDate();
	}

}
